<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <!-- 信息 -->
    <link rel="icon" href="/favicon.ico" type="image/x-icon" />
    <title>admin-varlet</title>
    <meta name="author" content="尘跃" />

    <link rel="stylesheet" href="/css/style-varlet.css">
    <link rel="stylesheet" href="/css/admin-varlet.css">

    <!-- 百度统计 -->
    <script src="/js/tongji.js"></script>
    <!-- Vue3 -->
    <script src="/js/vue/vue.global.prod.js"></script>
    <!-- Vue UI LIB -->
    <script src="/js/vue/varlet.js"></script>
    <script src="/js/third/touch-emulator.js"></script>
    <!-- WX JS SDK -->
    <script src="/js/wx.js"></script>


    <style>
        #panel-main {
            box-sizing: border-box;
            padding: 1em;

            height: 80%;
            overflow-y: auto;
        }

        #panel-manage {
            box-sizing: border-box;
            padding: 1em;

            height: 80%;
            overflow-y: auto;
        }

        #panel-edit {
            box-sizing: border-box;
            padding: 1em;

            height: 80%;
            overflow-y: auto;
        }


        #panel-information {
            box-sizing: border-box;
            padding: 1em;

            height: 80%;
            overflow-y: auto;
        }
    </style>
</head>

<body>
    <div id="app"></div>


    <script src="/js/http.js"></script>
    <script>
        const lightThemeMD2 = null;
        const viewportDarkThemeMD2 = Varlet.Themes.toViewport(Varlet.Themes.dark);
        const viewportLightThemeMD3 = Varlet.Themes.toViewport(Varlet.Themes.md3Light);
        const viewportDarkThemeMD3 = Varlet.Themes.toViewport(Varlet.Themes.md3Dark);

        Varlet.StyleProvider(viewportLightThemeMD3);
        const app = Vue.createApp({
            template: `
                <!-- 标题栏 -->
                <header>
                    <var-app-bar title="admin-varlet">
                        <template #right>

                            <var-menu-select
                                v-model="theme"
                                placement="top-start"
                            >
                                <var-button
                                    color="transparent"
                                    text-color="#fff"
                                    round
                                    text
                                >
                                    <var-icon name="palette" :size="32"></var-icon>
                                </var-button>
                            
                                <template #options>
                                    <var-menu-option label="MD2亮色" value="light_md2"/>
                                    <var-menu-option label="MD2暗色" value="dark_md2"/>
                                    <var-menu-option label="MD3亮色" value="light_md3"/>
                                    <var-menu-option label="MD3暗色" value="dark_md3"/>
                                </template>
                            </var-menu-select>

                        </template>
                    </var-app-bar>
                </header>

                <!-- 底部导航 -->
                <var-bottom-navigation
                    id="navigation"
                    v-model:active="activeNav"
                    @change="handleNavigationChange"
                    :fixed="true"
                >
                    <var-bottom-navigation-item label="首页" icon="home" />
                    <var-bottom-navigation-item label="文章管理" icon="menu" />
                    <var-bottom-navigation-item label="编辑文章" icon="xml" />
                    <var-bottom-navigation-item label="个人信息" icon="account-circle" />
                </var-bottom-navigation>


                <!-- 首页 -->
                <div
                    v-show="activeNav === 0"
                    id="panel-main"
                >
                    该版本后台，开发陷入停滞；因为校园网，访问不了文档。
                </div>


                <!-- 文章管理 -->
                <div
                    v-show="activeNav === 1"
                    id="panel-manage"
                >
                    <var-list
                        :finished="articleFinished"
                        v-model:loading="articleDataSourceLoading"
                        @load="loadArticleNextPage()"
                    >
                        <var-cell :key="article.id" v-for="article in articleDataSource">
                            <var-card
                                :title="article.title"
                                :subtitle="article.sort_name + ' ' + article.date"
                            >
                                <!-- 描述 -->
                                <template #description>
                                    <div class="var-card__description">
                                        {{ article.content }}
                                    </div>
                                </template>

                                <template #extra>
                                    <var-space>
                                        <var-button @click="openURL('/pages/article.html?id=' + article.id)">
                                            查看
                                        </var-button>
                                        <var-button type="primary" :data-id="article.id" @click="updateArticle">修改</var-button>
                                        <var-button type="danger" :data-id="article.id" @click="deleteArticle">删除</var-button>
                                    </var-space>
                                </template>
                            </var-card>
                        </var-cell>
                        
                    </var-list>
                    
                </div>


                <!-- 编辑文章 -->
                <div
                    v-show="activeNav === 2"
                    id="panel-edit"
                >
                    <var-space direction="column" size="large">
                        
                    </var-space>
                </div>


                <!-- 个人信息 -->
                <div
                    v-show="activeNav === 3"
                    id="panel-information"
                >
                    <div
                        style="text-align: center;margin-top: 1em;"
                    >
                        <var-avatar
                            :src="userInformation.avatar"
                            :size="200"
                        />
                        <p style="font-size: 1.25em;">{{ userInformation.nickname }}</p>
                        <p><time :datetime="userInformation.register_time">{{ userInformation.register_time }}</time></p>
                    </div>
                    <var-divider description="" />
                    <div>
                        <var-list>
                            <var-cell>
                                目前发布了 {{ userInformation.articleCount }} 篇文章
                            </var-cell>
                        </var-list>
                    </div>
                    <var-divider description="最近更新的文章" />
                    <div>
                        <var-list>
                            <var-cell :key="item.id" v-for="item in articleDataSource.slice(0, 10)">
                                <var-link
                                    type="primary"
                                    :href="'/pages/article.html?id=' + item.id"
                                    target="_blank"
                                >
                                    {{ item.title }}
                                </var-link>
                            </var-cell>
                        </var-list>
                    </div>
                </div>
            `,

            async mounted() {
                const that = this;

                // 判断登录
                this.accessToken  = window.localStorage.getItem("token");
                if (!this.accessToken)
                {
                    await Varlet.Dialog({
                        title: "提示",
                        message: "未登录",
                        confirmButton: true,
                        cancelButton: false,
                        closeOnClickOverlay: false,
                        onClosed: function() {
                            window.location.assign("./login.html");
                        }
                    });
                    return;
                }

                // 判断 token 是否有效
                // axios.defaults.headers.common['token'] = this.accessToken;
                await HTTP.setHeaders({
                    token: this.accessToken
                });
                HTTP.request({
                    method: "GET",
                    url: "/api/user/verifyToken"
                }).then(async response => {
                    const result = response.data;
                    if (!result.data)
                    {
                        window.localStorage.setItem("token", null);
                        window.localStorage.setItem("username", null);
                        await Varlet.Dialog({
                            title: "提示",
                            message: "认证失效！请重新登录。",
                            confirmButton: true,
                            cancelButton: false,
                            closeOnClickOverlay: false,
                            onClosed: function() {
                                window.location.assign("./login.html");
                            }
                        });
                    }
                });

                
                // 初始化 面板高度
                this.updatePanelHeight();
                window.addEventListener("resize", this.updatePanelHeight);


                // 获取用户信息
                const username = window.localStorage.getItem("username");
                const userInfoResponse = await HTTP.request({
                    method: "GET",
                    url: "/api/user/username/" + username
                });
                const result = userInfoResponse.data;
                if (result.type === "success")
                {
                    this.userInformation = result.data;

                    // 获取头像
                    const avatarResponse = await HTTP.request({
                        method: "GET",
                        url: "/api/avatar/" + this.userInformation.avatar_id
                    });
                    const avatarResult = avatarResponse.data;
                    if (avatarResult.type === "success")
                    {
                        this.userInformation.avatar = avatarResult.data.content;
                    }

                    // 获取发布的文章数量
                    const articleCountResponse = await HTTP.request({
                        method: "GET",
                        url: "/api/article/count/user/username/" + username
                    });
                    const articleCountResult = articleCountResponse.data;
                    if (articleCountResult.type === "success")
                    {
                        this.userInformation.articleCount = articleCountResult.data;
                    }
                }


                // articleDataSource
                this.loadArticleNextPage();
            },


            data() {
                return {
                    theme: "light",
                    activeNav: 0,

                    loadedArticlePage: 0,
                    articleDataSource: [],
                    articleDataSourceLoading: false,
                    articleFinished: false,

                    userInformation: {},
                };
            },


            watch: {
                // 每当 theme 改变时，这个函数就会执行
                theme(newTheme, _oldTheme) {
                    // console.log(newTheme);
                    if (newTheme === "light_md3") {
                        Varlet.StyleProvider(viewportLightThemeMD3);
                    } else if (newTheme === "dark_md3") {
                        Varlet.StyleProvider(viewportDarkThemeMD3);
                    } else if (newTheme === "light_md2") {
                        Varlet.StyleProvider(lightThemeMD2);
                    } else if (newTheme === "dark_md2") {
                        Varlet.StyleProvider(viewportDarkThemeMD2);
                    }
                    this.updatePanelHeight();
                }
            },

            methods: {

                // 更新面板高度
                updatePanelHeight() {
                    const header = document.getElementsByTagName("header")[0];
                    const nav = document.getElementById("navigation");
                    const headerHeight = parseInt(window.getComputedStyle(header).height);
                    const navHeight = parseInt(window.getComputedStyle(nav).height);
                    const panelHeight = window.innerHeight - headerHeight - navHeight;
                    const panelHeightStyle = `${panelHeight}px`;
                    document.getElementById("panel-main").style.height = panelHeightStyle;
                    document.getElementById("panel-manage").style.height = panelHeightStyle;
                    document.getElementById("panel-edit").style.height = panelHeightStyle;
                    document.getElementById("panel-information").style.height = panelHeightStyle;
                },

                handleNavigationChange() {
                    if (this.activeNav === 1 && !this.articleDataSource)
                    {
                        this.loadArticleNextPage();
                    }
                },

                openURL(url) {
                    window.open(url);
                },

                
                // manage
                async loadArticleNextPage(reload = false)
                {
                    if (reload)
                    {
                        this.articleFinished = false;
                        this.loadedArticlePage = 0;
                        this.articleDataSource = [];
                        this.articleDataSourceLoading = true;
                    }
                    if (this.articleFinished)
                    {
                        this.articleDataSourceLoading = false;
                        return;
                    }
                    if (this.articleDataSource.length >= this.userInformation.articleCount)
                    {
                        this.articleFinished = true;
                        this.articleDataSourceLoading = false;
                        return;
                    }

                    this.articleDataSourceLoading = true;
                    const username = window.localStorage.getItem("username");
                    const response = await HTTP.request({
                        method: "GET",
                        url: `/api/article/user/username/${username}/page/${this.loadedArticlePage + 1}`
                    })
                    const result = response.data;
                    if (result.type === "success")
                    {
                        for(article of result.data)
                        {
                            if (article.content.length > 200)
                            {
                                article.content = article.content.substring(0, 200) + "......";
                            }
                        }
                        this.articleDataSource.push(...result.data);
                        this.articleDataSourceLoading = false;
                        this.loadedArticlePage++;
                    }
                    
                },

                

                async updateArticle(e)
                {
                    const that = this;
                    const articleID = e.target.dataset.id;

                    Varlet.Dialog({
                        title: "提示",
                        message: "暂未开发",
                        confirmButton: true,
                        cancelButton: false,
                        closeOnClickOverlay: false
                    });
                },


                async deleteArticle(e)
                {
                    const that = this;
                    const articleID = parseInt(e.target.dataset.id);

                    Varlet.Dialog({
                        title: "提示",
                        message: "是否删除",
                        closeOnClickOverlay: false,
                        onConfirm: async function() {
                            if (!articleID)
                            {
                                await Varlet.Dialog({
                                    title: "提示",
                                    message: "删除失败",
                                    confirmButton: true,
                                    cancelButton: false,
                                    closeOnClickOverlay: false,
                                });
                                return;
                            }
                            HTTP.request({
                                method: "DELETE",
                                url: "/api/article",
                                data: {
                                    id: articleID
                                }
                            }).then(async response => {
                                const result  =  response.data;

                                await Varlet.Dialog({
                                    title: "提示",
                                    message: result.message,
                                    confirmButton: true,
                                    cancelButton: false,
                                    closeOnClickOverlay: false,
                                });
                                if (result.type === "success")
                                {
                                    that.updateArticleDataSource();
                                }

                            });
                        }
                    });

                },


                // edit


                // userInformation


            }
        })
        app.use(Varlet).mount('#app');
    </script>
</body>


</html>

